﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace RSProject
{
    public static class ColorspaceHelper
    {
        public static HSI RGB2HSI(RGB rgb)
        {
            HSI hsi = new HSI();

            double r = (rgb.Red / 255.0);
            double g = (rgb.Green / 255.0);
            double b = (rgb.Blue / 255.0);

            double theta = Math.Acos(0.5 * ((r - g) + (r - b)) / Math.Sqrt((r - g) * (r - g) + (r - b) * (g - b))) / (2 * Math.PI);

            hsi.Hue = (b <= g) ? theta : (1 - theta);
            hsi.Saturation = 1 - 3 * Math.Min(Math.Min(r, g), b) / (r + g + b);
            hsi.Intensity = (r + g + b) / 3;
            
            return hsi;
        }

        public static RGB HSI2RGB(this HSI hsi)
        {
            double r, g, b;

            double h = hsi.Hue;
            double s = hsi.Saturation;
            double i = hsi.Intensity;

            h = h * 2 * Math.PI;
            if (h >= 0 && h < 2 * Math.PI / 3)
            {
                b = i * (1 - s);
                r = i * (1 + s * Math.Cos(h) / Math.Cos(Math.PI / 3 - h));
                g = 3 * i - (r + b);
            }
            else if (h >= 2 * Math.PI / 3 && h < 4 * Math.PI / 3)
            {
                r = i * (1 - s);
                g = i * (1 + s * Math.Cos(h - 2 * Math.PI / 3) / Math.Cos(Math.PI - h));
                b = 3 * i - (r + g);
            }
            else
            {
                g = i * (1 - s);
                b = i * (1 + s * Math.Cos(h - 4 * Math.PI / 3) / Math.Cos(5 * Math.PI / 3 - h));
                r = 3 * i - (g + b);
            }

            return new RGB((byte)(r*255.0+0.5), (byte)(g * 255.0 + 0.5), (byte)(b * 255.0 + 0.5));
        }
    }
}
